package com.speakershare;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SpeakerShare extends Activity implements Runnable {
	
	ServerSocket serverSocket;
	Socket socket;
	Thread t;
	
	TextView tv;
	TextView ip;
	Button exitButton;
	String text;
	
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();
    
    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("speakershare", "Application started.");                 
        setContentView(R.layout.main);
        
        // Enumerate all IP addresses and show the first one on the screen
        ArrayList<String> ipAddresses = new ArrayList<String>();
        ip = (TextView) findViewById(R.id.IP);
        try {
        	Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        	while(e.hasMoreElements()){
        		NetworkInterface nic = e.nextElement();
        		Enumeration<InetAddress> f = nic.getInetAddresses();
        		while(f.hasMoreElements()){
        			InetAddress ia = f.nextElement();
        			String address = ia.getHostAddress();
        			Log.v("speakershare", address);
        			if(!address.equals("127.0.0.1"))
        				ipAddresses.add(address); // Discard localhost address
        		}
        	}
        	if(ipAddresses.size() > 0)
        		ip.setText(ipAddresses.get(0)); // Show the first IP address
		} catch (SocketException e) { }
        
        tv = (TextView) findViewById(R.id.TextView01);
        exitButton = (Button) findViewById(R.id.Button01);
        exitButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				SpeakerShare.this.finish();
			}
		});
        
        t = new Thread(this);
        t.start();
    }
    
    public void onDestroy(){
    	super.onDestroy();
    	
    	// Close client socket
    	if(socket != null){
			try {
				socket.close();
			} catch (IOException e) {}
		}
    	
    	// Close server socket
    	if(serverSocket != null){
			try {
				serverSocket.close();
			} catch (IOException e) {}
		}
    }
    
    private void updateResultsInUi() {

        // Back in the UI thread -- update our UI elements based on the data in mResults
        tv.setText(text);
    }
    
    public void run() {
    	AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, 44100*4, AudioTrack.MODE_STREAM);
    	audioTrack.play();
    	
        try {
			serverSocket = new ServerSocket(6477);
			while(true){
				text = "Listening on port tcp/6477";
				mHandler.post(mUpdateResults);		

				socket = serverSocket.accept();
				try {
					
					text = "Client connected from:\n" + socket.getRemoteSocketAddress().toString();
					mHandler.post(mUpdateResults);
					
					DataInputStream in = new DataInputStream(socket.getInputStream());
					byte[] buffer = new byte[44100]; // 250 ms
					while(true){
						in.readFully(buffer);
						audioTrack.write(buffer, 0, buffer.length);
					}
				}catch (IOException ex){
					Log.e("speakershare", ex.getMessage() + "\nread error");
				}
			}
		} catch (IOException ex) {
			Log.e("speakershare", ex.getMessage() + "\naccept error");
		}
		
		audioTrack.flush();
		audioTrack.stop();
		audioTrack.release();
	}
}